package cn.stronglink.esm27.collection.iot.devices.algorithmservice.task;

import java.util.Date;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Preconditions;

import cn.stronglink.esm27.collection.core.util.ContextUtils;
import cn.stronglink.esm27.collection.iot.devices.algorithmservice.algorithm.GasDispersionAlgorithmFactory;
import cn.stronglink.esm27.collection.iot.devices.algorithmservice.algorithm.IAlgorithm;
import cn.stronglink.esm27.collection.iot.devices.algorithmservice.algorithm.IAlgorithmFactory;
import cn.stronglink.esm27.collection.iot.devices.algorithmservice.entity.GasAlgorithmManager;
import cn.stronglink.esm27.collection.iot.devices.algorithmservice.entity.GasDispersionParamsEntity;
import cn.stronglink.esm27.collection.iot.devices.esm27.message.MQMessageOfESM27;
import cn.stronglink.esm27.collection.mq.TopicSender;

@Component("autoPushGasAlgorithmDatasTask")
@Lazy(false)
@EnableScheduling
public class AutoPushGasAlgorithmDatasTask implements SchedulingConfigurer {
	private static Logger logger = LogManager.getLogger(AutoPushGasAlgorithmDatasTask.class.getName());
	private TopicSender topicSender = (TopicSender) ContextUtils.getBean("topicSender");
	private final static String TOPIC_NAME = "ESM27AlgorithmToService";
	private final static String ACTION_CODE = "GasDispersionAlgorithmResult"; // MQ涓垽鏂秷鎭被鍨嬬殑鏍囪瘑绗�
	private static final String DEFAULT_CRON = "0/5 * * * * ? ";
	private String cron = DEFAULT_CRON;
	private IAlgorithm algorithm;
	private boolean isRun = false;

	public AutoPushGasAlgorithmDatasTask() {
		IAlgorithmFactory algorithmFactory = new GasDispersionAlgorithmFactory();
		this.algorithm = algorithmFactory.createAlgorithm();
	}

	/**
	 * 鑾峰彇浠诲姟鎵ц瑙勫垯
	 * 
	 * @return
	 */
	public String getCron() {
		return cron;
	}

	/**
	 * 璁剧疆浠诲姟鎵ц瑙勫垯
	 * 
	 * @param cron
	 */
	public void setCron(String cron) {
		if (cron == null || cron.isEmpty()) {
			isRun = false;
		} else {
			this.cron = cron;
			isRun = true;
		}
	}

	@Override
	public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
		taskRegistrar.addTriggerTask(new Runnable() {
			@Override
			public void run() {
				if (isRun == false)
					return;
				Object gasAlgorithmValues = this.calcGasResult();  // 璁＄畻姘斾綋鎵╂暎
				this.sendToMQ(gasAlgorithmValues);
//				try {
//					List<double[]> gasAlgorithmValues = this.calcGasResult();  // 璁＄畻姘斾綋鎵╂暎
//					this.sendToMQ(gasAlgorithmValues);				  // 鍙戦�佹皵浣撴墿鏁ｆ暟鎹埌MQ
//				} catch (Exception e) {
//					logger.error(e);
//				}
			}

			/**
			 * 璁＄畻姘斾綋鏁版嵁
			 * @return
			 */
			private Object calcGasResult() {
				GasDispersionParamsEntity gasParams = GasAlgorithmManager.getGasDispersionParams();
				Preconditions.checkNotNull(gasParams);

				Object[] params = new Object[] { gasParams.getAs(),gasParams.getWs(), gasParams.getWd(), gasParams.getGd(),
						gasParams.getH(), gasParams.getDq(), gasParams.getfCurrentTime(),gasParams.getConcentration() };
				AutoPushGasAlgorithmDatasTask.this.algorithm.updateParams(params);
				gasParams.setfCurrentTime(gasParams.getfCurrentTime()+gasParams.getPushSpanSecond());
				
				return AutoPushGasAlgorithmDatasTask.this.algorithm.calc();
			}

			/**
			 * 鍙戦�佽绠楃粨鏋滃埌鎸囧畾MQ
			 * @param value
			 */
			private void sendToMQ(Object values) {
				MQMessageOfESM27 message = new MQMessageOfESM27();
				message.setActioncode(ACTION_CODE);
				message.setTimeStamp(System.currentTimeMillis());
				message.setAwsPostdata(values);
				message.setIsSuccess(true);

				String json = JSON.toJSONString(message);
				topicSender.send(TOPIC_NAME, json);
				logger.info("鍙戦�乕{}]鍒癕Q瀹屾垚:{}", "璁＄畻姘斾綋鎵╂暎妯″瀷鐨勪俊鎭�", json);
			}
		}, new Trigger() {
			@Override
			public Date nextExecutionTime(TriggerContext triggerContext) {
				// 浠诲姟瑙﹀彂锛屽彲淇敼浠诲姟鐨勬墽琛屽懆鏈�
				CronTrigger trigger = new CronTrigger(cron);
				Date nextExec = trigger.nextExecutionTime(triggerContext);
				return nextExec;
			}
		});
	}
}
